#!/bin/bash

# 导入副将数据脚本
# 使用方法: ./run-import-deputy-general.sh

echo "🚀 开始运行副将数据导入脚本..."

# 检查是否在正确的目录
if [ ! -f "import-deputy-general-data.js" ]; then
    echo "❌ 请在 nestjs-app 目录下运行此脚本"
    exit 1
fi

# 检查数据文件是否存在
if [ ! -f "websocket_data_2025-08-27T09-19-03-318Z.json" ]; then
    echo "❌ 数据文件不存在: websocket_data_2025-08-27T09-19-03-318Z.json"
    exit 1
fi

# 检查数据库表是否存在
echo "🔍 检查数据库表..."
node -e "
const mysql = require('mysql2/promise');
const dbConfig = {
  host: process.env.DB_HOST || '43.143.253.188',
  port: parseInt(process.env.DB_PORT) || 3306,
  user: process.env.DB_USER || 'nextjs',
  password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
  database: process.env.DB_NAME || 'nextjs',
  timezone: '+08:00'
};

async function checkTable() {
  try {
    const connection = await mysql.createConnection(dbConfig);
    const [tables] = await connection.execute(\`
      SELECT COUNT(*) as count 
      FROM information_schema.tables 
      WHERE table_schema = ? AND table_name = 'deputy_general_base'
    \`, [dbConfig.database]);
    
    if (tables[0].count === 0) {
      console.log('❌ 表 deputy_general_base 不存在，请先运行 create-deputy-general-table.sql 创建表');
      process.exit(1);
    }
    
    console.log('✅ 表 deputy_general_base 存在');
    await connection.end();
  } catch (error) {
    console.error('❌ 检查表时发生错误:', error.message);
    process.exit(1);
  }
}

checkTable();
"

if [ $? -ne 0 ]; then
    echo "❌ 表检查失败，请先创建表"
    exit 1
fi

# 运行导入脚本
echo "📥 开始导入数据..."
node import-deputy-general-data.js

if [ $? -eq 0 ]; then
    echo "🎉 导入完成！"
else
    echo "❌ 导入失败！"
    exit 1
fi 